using System;
using Impact.Controllers;
using Impact.Web.Foundation.Controls;
using Impact.Model.Objects;

namespace Impact.Web.Admin
{
    public partial class EditProfile : Impact.Web.Foundation.PageBase, Impact.Views.IProfileEditorView
    {
        private ProfileController controller;

        /// <summary>
        /// override of onload to perform startup functionality
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            controller = new ProfileController( this, UserId );
            controller.InitializeEditor( !IsPostBack );
        }

        /// <summary>
        /// event handler for the submit button
        /// </summary>
        protected void SubmitCommand( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                controller.SaveProfile();
                MessageBox.Show( "Your changes have been saved." );
                Redirect( "~/Admin/Profiles.aspx" );
            }
        }

        /// <summary>
        /// event handler for the cancel button
        /// </summary>
        protected void CancelCommand( object sender, EventArgs e )
        {
            Redirect( "~/Admin/Profiles.aspx" );
        }

        #region IProfileEditorView Members

        /// <summary>
        /// populate form elements with data from the given event
        /// </summary>
        public void PopulateForm( Profile profile )
        {
            ViewState[Profile.Columns.ProfileID] = profile.ProfileID;

            companyName.Text = profile.CompanyName;
            website.Text = profile.Website;
            address.Text = profile.Address;
            city.Text = profile.City;
            state.SelectedValue = profile.State;
            zipcode.Text = profile.Zipcode;
        }

        /// <summary>
        /// populate an Event object with data from the form elements
        /// </summary>
        public Profile RetrieveFormData()
        {
            Profile profile = null;
            if ( ViewState[Profile.Columns.ProfileID] != null )
            {
                int profileId = (int)ViewState[Profile.Columns.ProfileID];
                if ( profileId > 0 )
                {
                    profile = ProfileController.GetProfile( profileId );
                }
            }

            if ( profile == null )
            {
                profile = new Profile();
            }

            profile.CompanyName = companyName.Text;
            profile.Website = website.Text;
            profile.Address = address.Text;
            profile.City = city.Text;
            profile.State = state.SelectedValue;
            profile.Zipcode = zipcode.Text;

            return profile;
        }

        #endregion
    }
}
